﻿using System;
using System.Configuration;
using System.Linq;
using System.ServiceModel;
using System.ServiceModel.Configuration;

namespace RockBus.ServiceModel
{
    public class ConfigurationHelper
    {
        public static ServiceElement GetServiceElement(string serviceTypeFullName)
        {
            var servicesSection = (ServicesSection)ConfigurationManager.GetSection("system.serviceModel/services");
            if (servicesSection.Services.ContainsKey(serviceTypeFullName))
            {
                return servicesSection.Services[serviceTypeFullName];
            }

            return null;
        }

        public static ServiceElement GetServiceElement<TService>()
        {
            return GetServiceElement(typeof(TService).FullName);
        }

        public static UriSchemeKeyedCollection GetBaseAddresses<TService>()
        {
            return GetBaseAddresses(typeof(TService).FullName);
        }

        public static UriSchemeKeyedCollection GetBaseAddresses(string serviceTypeFullName)
        {
            var baseAddresses = new UriSchemeKeyedCollection();

            var serviceElement = GetServiceElement(serviceTypeFullName);
            if (serviceElement == null)
            {
                return baseAddresses;
            }

            foreach (var baseAddressElement in serviceElement.Host.BaseAddresses.Cast<BaseAddressElement>())
            {
                baseAddresses.Add(new Uri(baseAddressElement.BaseAddress, UriKind.Absolute));
            }

            return baseAddresses;
        }

        public static Uri GetUri(Uri baseUri, string path)
        {
            if (path.StartsWith("/", StringComparison.Ordinal) || path.StartsWith("\\", StringComparison.Ordinal))
            {
                int num = 1;
                while (num < path.Length && (path[num] == '/' || path[num] == '\\'))
                {
                    num++;
                }
                path = path.Substring(num);
            }
            if (path.Length == 0)
            {
                return baseUri;
            }
            if (!baseUri.AbsoluteUri.EndsWith("/", StringComparison.Ordinal))
            {
                baseUri = new Uri(baseUri.AbsoluteUri + "/");
            }
            return new Uri(baseUri, path);
        }
    }
}
